package com.xinenhua.businessserver.main;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.oasis.oasislib.base.BaseFragment;
import com.oasis.oasislib.utils.LogUtil;

import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.MainActivity;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.buildd.HotBuilding;
import com.xinenhua.businessserver.fictitious.FictitiousHouseList;
import com.xinenhua.businessserver.house.EntityHouseList;
import com.xinenhua.businessserver.house.FicHouseList;
import com.xinenhua.businessserver.http.BaseHttp;


import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.lzh.framework.updatepluginlib.UpdateConfig;
import org.lzh.framework.updatepluginlib.base.UpdateParser;
import org.lzh.framework.updatepluginlib.model.Update;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 *   app主页中的第一个fragment
 */
@ContentView(R.layout.main)
public class MainFragment extends BaseFragment<MainActivity> implements OnItemClickListener {


    @ViewInject(R.id.convenientBanner)
    private ConvenientBanner convenientBanner;
    private List<BannerItem> networkImages = new ArrayList<>();

    protected ImageLoader imageLoader;

    @ViewInject(R.id.warpper_message)
    RelativeLayout warpper_message;

    //实体图片
    @ViewInject(R.id.shiti)
    ImageView shiti;

    //虚拟图片
    @ViewInject(R.id.xuni)
    ImageView xuni;

    //热门楼盘
    @ViewInject(R.id.remen)
    ImageView remen ;

    @ViewInject(R.id.search)
    RelativeLayout search;

    @Override
    protected void start(){
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));
        //new QBadgeView(getActivity()).bindTarget(warpper_message).setBadgeNumber(7).setBadgeGravity(Gravity.END | Gravity.TOP).setBadgeTextSize(6,true);

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));

        //跳转实体房源
        shiti.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivity(), EntityHouseList.class);
                startActivity(intent);
            }
        });

        //跳转虚拟房源
        xuni.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivity(), FicHouseList.class);
                startActivity(intent);
            }
        });

        remen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivity(), HotBuilding.class);
                startActivity(intent);
            }
        });

        //搜索框也是跳转热门房源
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivity(), EntityHouseList.class);
                startActivity(intent);
            }
        });


        getBanner();
        update();
    }

    //自动更新
    private void update(){

        UpdateConfig.getConfig()
                // url 与 checkEntity方法可任选一种填写，且至少必填一种。
                // 数据更新接口数据，此时默认为使用GET请求
                .setUrl(Const.update+"?appstyle=2") //1是客户端 2 是服务端
                .setUpdateParser(new UpdateParser() {
                    @Override
                    public Update parse(String response) throws Exception {
                  /* 此处根据上面url接口返回的数据response进行update类组装。框架内部会使用此组装的update实例判断是否需要更新以做进一步工作*/

                        LogUtil.e(TAG,"response----"+response);
                        JsonObject returnData = new JsonParser().parse(response).getAsJsonObject();
                        JsonObject returnData1 = returnData.getAsJsonObject("data") ;

                        Update update = new Update();
                        update.setUpdateContent(returnData1.get("content").getAsString());
                        update.setForced(true);
                        update.setIgnore(false);
                        update.setVersionName(returnData1.get("version_name").getAsString());
                        update.setUpdateUrl(returnData1.get("url").getAsString());
                        update.setVersionCode(returnData1.get("version_code").getAsInt());

                        LogUtil.e(TAG,"update"+update);

                        return update;
                    }
                });
        UpdateBuilder.create().checkWithDaemon(20);

    }

    //得到轮播图
    private void getBanner(){
        Call call = BaseHttp.getCallWithUrlAndData(Const.servicebanner,null);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                System.out.println(rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);

                    JsonParser parser = new JsonParser();
                    JsonObject jsonObject = parser.parse(s).getAsJsonObject();

                    JsonArray jsonArray = jsonObject.get("service").getAsJsonArray();

                    List<BannerItem> items = new ArrayList<BannerItem>();

                    Iterator<JsonElement> iterator = jsonArray.iterator();
                    while (iterator.hasNext()){
                        JsonElement next = iterator.next();
                        JsonObject jo = next.getAsJsonObject();
                        String imageurl = jo.get("imageurl").getAsString();
                        String title = jo.get("title").getAsString();

                        BannerItem bannerItem = new BannerItem();
                        bannerItem.setImageurl(imageurl);
                        bannerItem.setTitle(title);

                        items.add(bannerItem);
                    }

                    networkImages.addAll(items);
                    //初始化轮播图
                    initImage();

                }else {
                    System.out.println(BaseHttp.getJsonMsg(rr));
                }

            }
        });
    }

    //配置轮播图
    private void initImage() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>(){

                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, networkImages)
                        //设置指示器是否可见
                        .setPointViewVisible(true)
                        //设置自动切换（同时设置了切换时间间隔）
                        .startTurning(2000)
                        //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                        //.setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                        //设置指示器的方向（左、中、右）
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                        //设置点击监听事件
                        .setOnItemClickListener(MainFragment.this)
                        //设置手动影响（设置了该项无法手动切换）
                        .setManualPageable(true);
            }
        });



    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.e(TAG,"onHiddenChanged  PersonalFragment   我的    "+  String.valueOf(hidden));
        if(hidden){
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));
        }else {
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.app_green));
        }

    }

    @Override
    public void onItemClick(int i) {
       // Toast.makeText(getActivity(), "position:" + i, Toast.LENGTH_SHORT).show();
    }
}

class NetworkImageHolderView implements Holder<BannerItem> {//String为传入的数据类型，可以更改为其他
   private ImageView imageView;
   @Override
   public View createView(Context context) {
       //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
       imageView = new ImageView(context);
       imageView.setScaleType(ImageView.ScaleType.FIT_XY);
       return imageView;
       //view = LayoutInflater.from(context).inflate(R.layout.banner_item, null, false);
       // return view;
   }

   @Override
   public void UpdateUI(Context context,int position, BannerItem data) {
       //imageView.setImageResource(R.drawable.);
       ImageLoader.getInstance().displayImage(data.getImageurl(),imageView);
   }
}




